//
//  AssetsCollectionViewController.swift
//  PhotoBrowser
//
//  Created by leotao on 16/5/29.
//  Copyright © 2016年 leotao. All rights reserved.
//

import UIKit
import SnapKit
import AssetsLibrary

private let reuseIdentifier = "Cell"
private let col = 4;
private let gap = 10;

class AssetsCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    var cellSize:CGSize!
    var collectionView:UICollectionView!
    var assetsGroup:ALAssetsGroup!
    var dataSource = [Photo]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

       
        initializeCollectionView();
        fetchAssets();
    }
    
    func initializeCollectionView() {
        let flowLayout = UICollectionViewFlowLayout();
        collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout);
        self.collectionView!.registerClass(AssetImageCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        let cellW = (self.view.bounds.width - (CGFloat(col) + 1) * CGFloat(gap)) / CGFloat(col);
        
//        let cellW = (self.view.bounds.width) / CGFloat(col);
        cellSize = CGSizeMake(cellW, cellW);
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.backgroundColor = UIColor.whiteColor();
        view.addSubview(collectionView);
        collectionView.snp_makeConstraints { (make) in
            make.edges.equalTo(self.view);
        }
    }
    
    func fetchAssets() {
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            self.assetsGroup.enumerateAssetsUsingBlock({ [unowned self](asset, index, stop) in
                if asset != nil {
                    let type = asset.valueForProperty(ALAssetPropertyType) as! String;
                    print(index);
                    if type == ALAssetTypePhoto {   // 是图片！
                        let photo = Photo(asset: asset);
                        self.dataSource.append(photo);
                    }
                } else {
                    print("asset = nil");
                    stop.initialize(true);
                    dispatch_async(dispatch_get_main_queue(), {
                        self.collectionView.reloadData()
                    })
                    
                    //                    stop.initialize(true);
                }

            })
        };
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource

    

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       
        return dataSource.count;
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as? AssetImageCell
        
        cell?.assets = dataSource[indexPath.row].asset;
    
        return cell!
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let browser = PhotoBrowser(delegate: self);
        browser.setCurrentPhotoIndex(indexPath.item);
        self.navigationController?.pushViewController(browser, animated: true);
    }
}

extension AssetsCollectionViewController: PhotoBrowserDelegate {
    func numberOfPhotos() -> Int {
        return self.dataSource.count;
    }
    
    func photoAtIndex(index: Int) -> Photo {
        
        return self.dataSource[index];
    }
}

extension AssetsCollectionViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return cellSize;
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
        return 10;
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
        return 0;
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
//        UIEdgeInsetsMake(<#T##top: CGFloat##CGFloat#>, <#T##left: CGFloat##CGFloat#>, <#T##bottom: CGFloat##CGFloat#>, <#T##right: CGFloat##CGFloat#>)
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }
}
